﻿using System.Collections.Generic;
using System.Security;

namespace Raven
{
    public class FuzzyModule
    {
        private Dictionary<string, FuzzyVariable> _variables = new Dictionary<string, FuzzyVariable>();

        private List<FuzzyRule> _rules = new List<FuzzyRule>();

        private void SetConfidencesOfConsequentsToZero()
        {
            foreach (var curRule in _rules)
            {
                curRule.SetConfidenceOfConsequentToZero();
            }
        }

        public FuzzyVariable CreateFLV(string varName)
        {
            _variables[varName] = new FuzzyVariable();
            return _variables[varName];
        }

        public void AddRule(FuzzyTerm antecedent, FuzzyTerm consequence)
        {
            _rules.Add(new FuzzyRule(antecedent, consequence));
        }

        public void Fuzzify(string nameOfFLV, Fix val)
        {
            Utility.Assert(_variables.ContainsKey(nameOfFLV), "<FuzzyModule::Fuzzify>:key not found");
            _variables[nameOfFLV].Fuzzify(val);
        }

        public Fix DeFuzzify(string nameOfFLV)
        {
            Utility.Assert(_variables.ContainsKey(nameOfFLV), "<FuzzyModule::DeFuzzifyMaxAv>:key not found");

            SetConfidencesOfConsequentsToZero();
            foreach (var curRule in _rules)
            {
                curRule.Calculate();
            }

            return _variables[nameOfFLV].DeFuzzifyMaxAv();
        }
    }
}